<?php

class StadiumsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
    
    public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
	    $model = $this->loadModel($id);
        if(isset($_POST['price']))
		{
		    $model->all_price = serialize($_POST['price']);
            $model->save();
		}
       
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Stadiums;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Stadiums']))
		{
			$model->attributes=$_POST['Stadiums'];
            $model->visible = 1;
			if($model->save())
				$this->redirect(array('admin'));
		}
        
        $arrTypes = StadiumTypes::model()->findAll();

		$this->render('create',array(
			'model'=>$model,
            'arrTypes'=>$arrTypes,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Stadiums']))
		{
			$model->attributes=$_POST['Stadiums'];
			if($model->save())
				$this->redirect(array('admin'));
		}
        
        $arrTypes = StadiumTypes::model()->findAll();

		$this->render('update',array(
			'model'=>$model,
            'arrTypes'=>$arrTypes,
		));
	}
	
	public function actionSplit()
	{
		$model = new Stadiums;
        
        if (isset($_POST['Stadiums']))
        {
            $model = $this->loadModel($_POST['Stadiums']['name']);
            $model->visible = 0;
            $model->save();
            $alias = substr($model->name, 0, 1);
            $number = substr($model->name, 1, strlen($model->name)-1);
            $aliasSplit = Yii::app()->settings->get('system', $alias.' split');
            $exist = Stadiums::model()->findAll(array(
                'condition' => 'name LIKE "'.$aliasSplit . $number.'%"',
            ));
            if (count($exist)) {
                Stadiums::model()->updateAll(array('visible' => 1), 'name LIKE "'.$aliasSplit . $number.'%"');
            } else {
                $stadiumTypes = StadiumTypes::model()->findAllByAttributes(array(
        			'size' => 5,
        		));
                
                $stadium = new Stadiums;
                $stadium->stadium_type_id = $stadiumTypes[0]->id;
                $stadium->name = $aliasSplit . $number . '-1';
                $stadium->visible = 1;
                $stadium->save();
                
                $stadium = new Stadiums;
                $stadium->stadium_type_id = $stadiumTypes[0]->id;
                $stadium->name = $aliasSplit . $number . '-2';
                $stadium->visible = 1;
                $stadium->save();
            }
        }
		
		$stadiumTypes = StadiumTypes::model()->findAllByAttributes(array(
			'size' => 7,
		));
		
		$listStadiums = array();
		foreach ($stadiumTypes as $type) {
			$listStadiums = CMap::mergeArray($listStadiums,Stadiums::model()->findAllByAttributes(array(
				'stadium_type_id' => $type->id,
                'visible' => 1,
			)));
		}
        
        $this->render('split', array(
            'model' => $model,
			'listStadiums' => $listStadiums,
		));
	}
    
    public function actionMerge()
    {
        $model = new Stadiums;
        
        if (isset($_POST['Stadiums']))
        {
            $arr = explode(' + ', $_POST['Stadiums']['name']);
            
            foreach ($arr as $value)
            {
                $stadium = Stadiums::model()->findByAttributes(array(
                    'name' => $value
                ));
                $stadium->visible = 0;
                $stadium->save();
            }
            
            $alias = substr($arr[0], 0, 1);
            $number = substr($arr[0], 1, strlen($model->name)-2);
            $aliasSplit = Yii::app()->settings->get('system', $alias.' merge');
            
            $stadium = Stadiums::model()->findByAttributes(array(
                'name' => $aliasSplit.$number
            ));
            $stadium->visible = 1;
            $stadium->save();
        }
        
        $listStadiums = Stadiums::model()->findAll(array(
			'condition' => 'name LIKE "%-1" AND visible = 1',
		));
        
        foreach ($listStadiums as $stadium)
            $stadium->name = $stadium->name . ' + ' . substr($stadium->name, 0, strlen($stadium->name)-1) . '2';
        
        $this->render('merge', array(
            'model' => $model,
			'listStadiums' => $listStadiums,
		));
    }

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Stadiums');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Stadiums('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Stadiums']))
			$model->attributes=$_GET['Stadiums'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
    
    /**
     * dunghd add 21/09/2011
     * check status of all satdium
     * */
    public function actionCheck()
    {        
        // Find current statadium
        $model=Jqcalendar::model()->findByAttributes(array('Stadium' => $_POST['stadium']),'StartTime <= :current AND EndTime >= :current', array('current'=> date('Y-m-d H:i:s') ));
		if($model===null)
			echo json_encode(array('value' => 0));
        else
        {
            echo json_encode(array('value' => 100*(strtotime(date('Y-m-d H:i:s')) - strtotime($model->StartTime)) /( strtotime($model->EndTime) - strtotime($model->StartTime) ) ));
        }		
    }
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Stadiums::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='Stadiums-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
